from mongoengine import *
from gheat import managers

# Create your models here.
class Point(Document):
    """
        A simple representation of a point inside the gheat database
    """
    # uid = models.CharField(max_length=100, name='unique identifier')
    latitude = FloatField(name='Latitude')
    longitude = FloatField(name='Longitude')
    modtime = DateTimeField(name='Last modification time')
    density = IntField(name='density of the current point')

    @staticmethod
    def points_inside(tile):
        '''
            Search all the points inside the Tile
        '''
        lat1, lat2, lng1, lng2 = tile.llbound
        qs = Point.objects.filter(
            latitude__lte=lat1,
            latitude__gte=lat2,
            longitude__lte=lng1,
            longitude__gte=lng2,
            density__gt=0
            )
        return qs

    @staticmethod
    def num_points(tile,modtime=None):
        '''
            Count the number of points in a tile for a certain time
        '''
        qs = Point.points_inside(tile)
        if modtime:
            qs.filter(modtime__gt=modtime)

        return len(qs)


    def clear_points(self):
        '''
            Clear all the points of the database
        '''
        Point.objects.delete()
        
    def upsert_point(self, lat, lon, lastmod, density):
        new_point = {'Latitude': lat, 'Longitude': lon, 'Last modification time': lastmod, 'density of the current point': density}
        Point.insert(new_point)
        
    def upsert_point_list(self, points):
        for lat, lon, lastmod, density in points:
            upsert_point(lat, lon, lastmod, density)
                